package org.fastiot.gateway.client

import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
import org.fastiot.gateway.Message
import org.fastiot.protocol.Packet

class BytePacketDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        def readableBytes = byteBuf.readableBytes()
        println "readableBytes:$readableBytes"
        def buff = byteBuf.readBytes(readableBytes)
        byte[] bytes = new byte[readableBytes]
        buff.getBytes(0, bytes)
        println "client.BytePacketDecoder:${bytes.encodeHex()}"

        if (bytes) {
            out.add(new Message(
                    direction: Packet.Direction.Upstream, dateReceived: new Date(),
                    metadata: [remoteAddress: ctx.channel().remoteAddress()], contents: bytes
            ))
        }
    }
}
